package com.software.frontend.mine.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {

    private final Handler handler;

    private final Integer SUCCESS_CODE;

    private final Integer FAIL_CODE;


    OkHttpClient client = new OkHttpClient();

    public DownLoadImageTask(Handler handler, Integer success_code, Integer fail_code) {
        this.handler = handler;
        SUCCESS_CODE = success_code;
        FAIL_CODE = fail_code;
    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        String url = urls[0];
        Bitmap bitmap = null;
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                byte[] bytes = Objects.requireNonNull(response.body()).bytes();
                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        Message msg = new Message();
        if (result != null) {
            msg.arg1 = SUCCESS_CODE;
            Bundle bundle = new Bundle();
            bundle.putParcelable("bitmap", result);
            msg.setData(bundle);
        }else {
            msg.arg1 = FAIL_CODE;
        }
        handler.sendMessage(msg);
    }
}
